package com.symaster.gameengine.test;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class HighFPSExample {

    private long window;
    private final int targetFPS = 240;  // 目标帧率，例如 240 Hz

    public void run() {
        System.out.println("LWJGL version: " + Version.getVersion());
        init();
        loop();
        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);
        glfwTerminate();
        glfwSetErrorCallback(null).free();
    }

    private void init() {
        GLFWErrorCallback.createPrint(System.err).set();
        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        // 配置 GLFW
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

        // 创建窗口
        window = glfwCreateWindow(800, 600, "High FPS Example", NULL, NULL);
        if (window == NULL) {
            throw new RuntimeException("Failed to create the GLFW window");
        }

        // 设置窗口上下文为当前线程
        glfwMakeContextCurrent(window);
        glfwSwapInterval(0); // 禁用 V-Sync
        glfwShowWindow(window);

        GL.createCapabilities(); // 初始化 OpenGL 上下文
    }

    private void loop() {
        // 设置清屏颜色
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        // 目标帧时间（以秒计）
        double frameTime = 1.0 / targetFPS;

        while (!glfwWindowShouldClose(window)) {
            // 记录开始时间
            double startTime = glfwGetTime();

            // 清除帧缓存
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            // 绘制三角形
            drawTriangle();

            // 交换颜色缓冲区
            glfwSwapBuffers(window);

            // 轮询事件
            glfwPollEvents();

            // 计算渲染结束时间
            double endTime = glfwGetTime();

            // 计算渲染一帧的实际时间
            double deltaTime = endTime - startTime;

            // 如果实际渲染时间小于目标帧时间，则睡眠
            if (deltaTime < frameTime) {
                try {
                    Thread.sleep((long) ((frameTime - deltaTime) * 1000)); // 将时间转换为毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void drawTriangle() {
        // 绘制三角形
        glBegin(GL_TRIANGLES);
        glColor3f(1.0f, 0.0f, 0.0f); // 顶点1 (红色)
        glVertex2f(-0.5f, -0.5f);

        glColor3f(0.0f, 1.0f, 0.0f); // 顶点2 (绿色)
        glVertex2f(0.5f, -0.5f);

        glColor3f(0.0f, 0.0f, 1.0f); // 顶点3 (蓝色)
        glVertex2f(0.0f, 0.5f);
        glEnd();
    }

    public static void main(String[] args) {
        new HighFPSExample().run();
    }
}
